import { useState, useMemo, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { usePortfolio } from '../context/PortfolioContext';
import WorkCard from '../components/WorkCard';
import Pagination from '../components/Pagination';

const Gallery = () => {
  const { works, searchTerm, loading, error, pagination, changePage, loadWorks } = usePortfolio();
  const [selectedCategory, setSelectedCategory] = useState('');
  const [searchParams] = useSearchParams();
  
  // 从URL参数获取课程信息
  const courseId = searchParams.get('courseId');
  const courseName = searchParams.get('courseName');

  // 当课程ID变化时重新加载作品
  useEffect(() => {
    if (courseId) {
      loadWorks(1, 12, courseId);
    } else {
      // 如果没有courseId，加载所有作品
      loadWorks(1, 12);
    }
  }, [courseId, loadWorks]);

  // 获取所有分类
  const categories = useMemo(() => {
    const cats = [...new Set(works.map(work => work.category).filter(Boolean))];
    return cats.sort();
  }, [works]);

  // 根据分类筛选作品
  const filteredWorks = useMemo(() => {
    if (!selectedCategory) return works;
    return works.filter(work => work.category === selectedCategory);
  }, [works, selectedCategory]);

  if (loading) {
    return (
      <div className="mt-6">
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-500 dark:text-gray-400">加载作品中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="mt-6">
        <div className="text-center py-12 bg-red-50 dark:bg-red-900/20 rounded-lg">
          <p className="text-red-600 dark:text-red-400">{error}</p>
          <button 
            onClick={() => window.location.reload()} 
            className="mt-4 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
          >
            重新加载
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="mt-6">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
        <h2 className="text-2xl font-semibold">
          {courseName ? `${courseName} - 作品展示` : 
           searchTerm ? `搜索结果: "${searchTerm}"` : '全部作品'}
          <span className="text-lg text-gray-500 dark:text-gray-400 ml-2">
            ({pagination.total})
          </span>
        </h2>
        
        {/* 分类筛选 */}
        {categories.length > 0 && (
          <div className="flex items-center gap-2">
            <label className="text-sm text-gray-600 dark:text-gray-400">分类:</label>
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">全部分类</option>
              {categories.map(category => (
                <option key={category} value={category}>
                  {category}
                </option>
              ))}
            </select>
          </div>
        )}
      </div>
      
      {filteredWorks.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 dark:bg-gray-800 rounded-lg">
          <p className="text-gray-500 dark:text-gray-400">
            {searchTerm ? '没有找到匹配的作品' : 
             selectedCategory ? `"${selectedCategory}"分类下暂无作品` : 
             '暂无作品，请联系管理员添加'}
          </p>
          {selectedCategory && (
            <button
              onClick={() => setSelectedCategory('')}
              className="mt-2 text-blue-600 dark:text-blue-400 hover:underline"
            >
              查看全部作品
            </button>
          )}
        </div>
      ) : (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
            {filteredWorks.map(work => (
              <WorkCard key={work.id} work={work} />
            ))}
          </div>
          
          {/* 分页组件 */}
          {pagination.totalPages > 1 && (
            <div className="mt-8 flex justify-center">
              <Pagination
                currentPage={pagination.page}
                totalPages={pagination.totalPages}
                totalItems={pagination.total}
                itemsPerPage={pagination.limit}
                onPageChange={changePage}
              />
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default Gallery;
